/**
 * @description 博客的控制层
 * @author 印明帝
 */
const { DEFAULT_PICTURE,REG_FOR_AT_WHO } = require('../conf/constant')
const { create,getBlogs } = require('../service/blog')
const { createAtRelation } = require('../service/atRelation')
const { SuccessModel, ErrorModel } = require('../model/ResModel')
const { createBlogFailInfo,getBlogFailInfo } = require('../model/errorInfo')

/**
 * 创建博客
 * @method createBlog
 * @param {Object} blogInfo 
 * @returns {Promise}
 */
async function createBlog({ userId, content, image }) {
  // 解析at关系，创建atRelation表
  let atList = []
  content = content.replace(REG_FOR_AT_WHO,(matchStr,nickName,id) => {
    atList.push(parseInt(id))
    return matchStr
  })
  // 创建blog
  let blog = await create({ userId, content, image })
  // 创建@关系
  await Promise.all(
    atList.map(userId => createAtRelation(userId, blog.id))
  )
  if(blog) {
    return new SuccessModel(blog)
  }
  return new ErrorModel(createBlogFailInfo)
}

/**
 * 
 * @param {*} ctx  koa2 ctx
 * @param {*} id 用户id
 * @param {*} index 查询列别分页页数
 */
async function getBlogList ({ctx,id,index}){
  // 如果index不存在就是查询首页，把index改为1
  if(!index) {
    index = 0
  }
  // 如果是currentId说明查询的用户是登录的用户
  if(id === 'currentId') {
    id = ctx.session.userInfo.id
  }
  // 把查询id，index转换成number类型
  id = parseInt(id)
  index = parseInt(index)
  // 调用函数
  let result = await getBlogs({id,index})
  if(result) {
    return new SuccessModel(result)
  }
  return new ErrorModel(getBlogFailInfo)
}
module.exports = {
  createBlog,
  getBlogList
}